//
//  SinaManager.m
//  SNS
//
//  Created by  on 11-11-19.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "SinaManager.h"
#import "ASIHTTPRequest.h"
#import "CoreDataManager.h"
#import "UserInfo.h"
#import "MBProgressHUD.h"
#import "TKAlertCenter.h"
#import "Reachability.h"

static SinaManager *sinaManagerSingleton = nil;

@implementation SinaManager


@synthesize sinaWeiBo = _sinaWeiBo;

+ (SinaManager *)sharedManager {
    if (!sinaManagerSingleton) {
        sinaManagerSingleton = [[SinaManager alloc] init];
    }
    return sinaManagerSingleton;
}

- (id) init {
    self = [super init];
    if (self) {
        _sinaWeiBo = [[WeiBo alloc] initWithAppKey:SinaWeiBo_APPKey
                                     withAppSecret:SinaWeiBo_APPSecret];
        _sinaWeiBo.delegate = self;
    }
    return self;
}

- (void) dealloc {
    [_sinaWeiBo release];
    
    [super dealloc];
}

- (void) login {
    if (![[Reachability reachabilityForInternetConnection] isReachable]) {
        [[TKAlertCenter defaultCenter] postAlertWithMessage:@"没有网络！"];
        return;
    }
    
	[_sinaWeiBo startAuthorize];
}

- (void) logout {
    [_sinaWeiBo LogOut];
}

- (void) updateStatus: (NSString *)newStatus
             delegate:(id)aDelegate 
       finishCallback:(SEL)aFinishCallback 
         failCallback:(SEL)aFailCallback {
    if (![[Reachability reachabilityForInternetConnection] isReachable]) {
        [[TKAlertCenter defaultCenter] postAlertWithMessage:@"没有网络！"];
        return;
    }
    
    self.delegate = aDelegate;
    self.finishCallback = aFinishCallback;
    self.failCallback = aFailCallback;
    
    [_sinaWeiBo postWeiboRequestWithText:newStatus
                                andImage:nil
                             andDelegate:self];
}

- (void) sendImage:(UIImage *)image withMsg:(NSString *)msg 
          delegate:(id)aDelegate 
    finishCallback:(SEL)aFinishCallback 
      failCallback:(SEL)aFailCallback {
    if (![[Reachability reachabilityForInternetConnection] isReachable]) {
        [[TKAlertCenter defaultCenter] postAlertWithMessage:@"没有网络！"];
        return;
    }
    
    self.delegate = aDelegate;
    self.finishCallback = aFinishCallback;
    self.failCallback = aFailCallback;
    
    [_sinaWeiBo postWeiboRequestWithText:msg
                                andImage:image
                             andDelegate:self];
}

- (void) getImageTimelineWithDelegate:(id<WBRequestDelegate>)aDelegate 
                                 page:(int)page {
    if (![[Reachability reachabilityForInternetConnection] isReachable]) {
        [[TKAlertCenter defaultCenter] postAlertWithMessage:@"没有网络！"];
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:1];
    [params setObject:@"2" forKey:@"feature"];
    [params setObject:[NSString stringWithFormat:@"%d", page] forKey:@"page"];
    
    [_sinaWeiBo requestWithMethodName:@"statuses/home_timeline.json"
                            andParams:params
                        andHttpMethod:@"GET"
                          andDelegate:aDelegate];
    
}

- (void)getVideoTimelineWithPage:(int)page 
                        delegate:(id)aDelegate 
                  finishCallback:(SEL)aFinishCallback 
                    failCallback:(SEL)aFailCallback {
    if (![[Reachability reachabilityForInternetConnection] isReachable]) {
        [[TKAlertCenter defaultCenter] postAlertWithMessage:@"没有网络！"];
        return;
    }
    
    self.delegate = aDelegate;
    self.finishCallback = aFinishCallback;
    self.failCallback = aFailCallback;
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:1];
    [params setObject:@"3" forKey:@"feature"];
    [params setObject:[NSString stringWithFormat:@"%d", page] forKey:@"page"];
    
    [_sinaWeiBo requestWithMethodName:@"statuses/home_timeline.json"
                            andParams:params
                        andHttpMethod:@"GET"
                          andDelegate:self];
}

- (void)getOriginURLFromShortURl:(NSString *)shortURL 
                        delegate:(id)aDelegate 
                  finishCallback:(SEL)aFinishCallback 
                    failCallback:(SEL)aFailCallback {
    if (![[Reachability reachabilityForInternetConnection] isReachable]) {
        [[TKAlertCenter defaultCenter] postAlertWithMessage:@"没有网络！"];
        return;
    }
    
    self.delegate = aDelegate;
    self.finishCallback = aFinishCallback;
    self.failCallback = aFailCallback;
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:1];
    [params setObject:shortURL forKey:@"url_short"];
    
    [_sinaWeiBo requestWithMethodName:@"short_url/expand.json"
                            andParams:params
                        andHttpMethod:@"GET"
                          andDelegate:self];
}

#pragma mark - WBRequestDelegate

- (void)request:(WBRequest *)request didFailWithError:(NSError *)error
{
    NSLog(@"%@", [error description]);
    
	if (self.delegate && [self.delegate respondsToSelector:self.failCallback]) {
        [self.delegate performSelector:self.failCallback withObject:[error description]];
    }
}

- (void)request:(WBRequest *)request didLoad:(id)result
{
    if (self.delegate && [self.delegate respondsToSelector:self.finishCallback]) {
        [self.delegate performSelector:self.finishCallback withObject:result];
    }
}

#pragma mark - WBSessionDelegate

- (void)weiboDidLogin {
    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow
                         animated:YES];
    
    self.delegate = self;
    self.finishCallback = @selector(getUserInfoFinish:);
    self.failCallback = @selector(getUserInfoFail:);
    
    [_sinaWeiBo requestWithMethodName:@"account/verify_credentials.json"
                            andParams:nil
                        andHttpMethod:@"GET"
                          andDelegate:self];
    
}

- (void)weiboLoginFailed:(BOOL)userCancelled withError:(NSError*)error {
    [[TKAlertCenter defaultCenter] postAlertWithMessage:@"登陆失败！"
                                                  image:[UIImage imageNamed:@"sinaIcon.png"]];
}

- (void)weiboDidLogout {
    [[TKAlertCenter defaultCenter] postAlertWithMessage:@"退出成功！"
                                                  image:[UIImage imageNamed:@"sinaIcon.png"]];
}

- (void)getUserInfoFinish:(id)result {
    
    NSDictionary *resultDic = (NSDictionary *)result;
    NSString *userName = [resultDic objectForKey:@"screen_name"];
    UserInfo *userInfo = (UserInfo *)[[CoreDataManager sharedManager] addNewObjectOfClass:[UserInfo class]];
    userInfo.name = userName;
    [[CoreDataManager sharedManager] saveContext];
    
    NSString *userImageURL = [resultDic objectForKey:@"profile_image_url"];
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:userImageURL]];
    request.delegate = self;
    request.didFailSelector = @selector(loadUserImageFail:);
    request.didFinishSelector = @selector(loadUserImageFinish:);
    [request startAsynchronous];
}

- (void)getUserInfoFail:(NSString *)errorInfo {
    [[TKAlertCenter defaultCenter] postAlertWithMessage:@"获取用户信息失败！"
                                                  image:[UIImage imageNamed:@"sinaIcon.png"]];
}

- (void)loadUserImageFail:(ASIHTTPRequest *)request {
    [[TKAlertCenter defaultCenter] postAlertWithMessage:@"读取头像失败！"
                                                  image:[UIImage imageNamed:@"sinaIcon.png"]];
}

- (void)loadUserImageFinish:(ASIHTTPRequest *)request {
    NSData *responseData = [request responseData];
    
    NSString *imagePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/avatar"];
    [responseData writeToFile:imagePath atomically:YES];
    
    [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow
                         animated:YES];
    
    [[TKAlertCenter defaultCenter] postAlertWithMessage:@"登陆成功！"
                                                  image:[UIImage imageNamed:@"sinaIcon.png"]];
}

@end
